package com.software.cool.api.app.v1.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.software.cool.api.admin.v1.vo.AdminLoginUserVO;
import com.software.cool.api.app.v1.service.impl.AppV1Service;
import com.software.cool.api.app.v1.vo.AppV1Result;
import com.software.cool.api.app.v1.vo.AppVO;
import com.software.cool.api.app.v1.vo.ParentLoginSessionVO;
import com.software.cool.api.app.v1.vo.ProjectTestDataVO;
import com.software.cool.constant.WeixinConstant;
import com.software.cool.entity.TbSysUser;
import com.software.cool.httpclient.HttpApiService;
import com.software.cool.api.admin.v1.controller.BaseController;
import com.software.cool.service.impl.TbSysUserService;
import com.software.cool.utils.WeixinUtils;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;


@Api(value = "APP端-v1接口", tags = "APP端-v1接口")
@RestController
@Slf4j
@RequestMapping("/app/v1")
@CrossOrigin
public class AppV1Controller extends BaseController {

    @Resource
    private AppV1Service appV1Service;
    @Resource
    private TbSysUserService sysUserService;
    @Autowired
    private HttpApiService httpApiService;
    @Value("${weixin.appId}")
    private String appId;
    @Value("${weixin.appSecret}")
    private String appSecret;



    @ApiOperation(value = "登录", notes = "登录")
    @GetMapping("/login")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userName", value = "账号", required = true, defaultValue = "admin"),
            @ApiImplicitParam(name = "password", value = "密码", required = true, defaultValue = "123321")
    })
    public AppV1Result<AdminLoginUserVO> login(@ApiParam(value = "账号") String userName, @ApiParam(value = "密码") String password, HttpServletRequest request){
        AdminLoginUserVO loginUser=appV1Service.login(userName,password,request);
        AppV1Result result=new AppV1Result();
        result.setSuccess(loginUser==null?false:true);
        result.setData(loginUser);
        return result;
    }


    @ApiOperation(value = "app账号修改密码", notes = "app账号修改密码")
    @GetMapping("/updatePwd")
    public AppV1Result updatePwd(String token,String password,String newPassword)throws Exception{
        TbSysUser model=new TbSysUser();
        model.setToken(token);
        model.setPassword(password);
        model.setNewPassword(newPassword);
        AppV1Result result=getAppUser(model.getToken());
        if(!result.isSuccess()){ return result; }
        AdminLoginUserVO loginUser=sysUserService.getAppLoginUser(token);
        boolean res=sysUserService.updatePwd(loginUser.getUserId(),password,newPassword);
        if(res){
            return AppV1Result.success();
        }else{
            return AppV1Result.fail("旧密码错误");
        }
    }

    @GetMapping("/wxLogin")
    public AppV1Result<ParentLoginSessionVO> weixinLogin(String code, String encryptedData, String iv) throws Exception {
        /**
         * 生成cookie的token
         */
        String tokenValue;

        /**
         * 家长ID
         */
        Long parentId;

        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + appSecret +"&js_code=" + code + "&grant_type=authorization_code";
        String body = httpApiService.doGet(url);
        JSONObject httpResult = JSON.parseObject(body);


        String sessionKey = httpResult.getString(WeixinConstant.SESSION_KEY);
        String openId = httpResult.getString(WeixinConstant.OPENID);
        log.info("家长端小程序登录成功: " + body);

        /**
         * 获取微信授权信息(比如电话)
         */
        JSONObject weixinUserInfo = WeixinUtils.getUserInfo(encryptedData,sessionKey,iv);
        String mobilePhone = weixinUserInfo.getString("phoneNumber");
//        /**
//         * 判断手机号码，用户是否存在（是否注册）
//         * 获取家长信息，如果没有，表示先需要注册
//         */
//        ParentDTO parentDTO = parentService.getParentByMobilePhone(mobilePhone);
//        if(parentDTO == null){
//
//            /**
//             * 表示没有注册，所以先给用户注册
//             */
//            parentDTO = parentService.register(mobilePhone, mobilePhone, CommonParentTypeEnum.PARENT_TYPE_UNKNOWN.getCode(), CommonParentRegisterResourceTypeEnum.PARENT_REGISTER_RESOURCE_TYPE_WECHAT.getCode(), openId, sessionKey);
//        }else{
//            /**
//             * 更新用户的openId
//             */
//            parentLoginService.updateWeixinInfo(parentDTO.getId(), openId, sessionKey);
//        }
//        parentId = parentDTO.getId();

        /**
         * 生成token的value
         */
        tokenValue = UUID.randomUUID().toString();

        /**
         * 设置Redis的token值
         */
//        stringRedisTemplate.opsForValue().set(String.format(RedisConstant.PARENT_TOKEN_TEMPLATE, tokenValue), openId,
//                TokenConstant.PARENT_EXPIRE,
//                TimeUnit.SECONDS);

        return AppV1Result.success(new ParentLoginSessionVO(openId, tokenValue),0);
    }

    @ApiOperation(value = "获取最新app版本", notes = "获取最新app版本")
    @GetMapping("/getLastedApp")
    public AppV1Result<AppVO> getLastedApp(HttpServletRequest request){
        return AppV1Result.success(appV1Service.getLastedApp(request),0);
    }


}
